<template>
  <div class="user-management-container">

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入用户名"
        clearable
        style="width: 200px; margin-right: 10px"
        @clear="fetchVoiceList"
      />
      <el-button type="primary" @click="fetchVoiceList">搜索</el-button>
    </div>

    <!-- 用户列表 -->
    <el-table :data="voiceList" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="text" label="识别文本" width="300" />
      <el-table-column prop="fileName" label="文件名" width="200" />
       <el-table-column label="音频播放" width="330">
        <template #default="scope">
          <!-- 假设 filePath 是可直接播放的 URL -->
          <audio v-if="scope.row.filePath" :src="getAudioUrl(scope.row.filePath)" controls></audio>
          <span v-else>无音频</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="150">
        <template #default="{row}">
          {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm') }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchVoiceList"
        @current-change="fetchVoiceList"
      />
    </div>

     <!-- 编辑对话框 -->
    <el-dialog 
      title="编辑语音记录" 
      v-model="editDialogVisible">
      <el-form :model="currentRecord" label-width="80px">
        <el-form-item label="识别文本">
          <el-input v-model="currentRecord.text"></el-input>
        </el-form-item>
        <!-- 根据需要可扩展其他字段 -->
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {getVoices , updateVoices , deleteUser} from '@/api/voiceManage'

// 在script setup顶部添加
import dayjs from 'dayjs'

// 语音记录列表
const voiceList = ref([])

// 控制编辑对话框显示
const editDialogVisible = ref(false)

// 当前待编辑的记录
const currentRecord = ref({})

const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取用户列表
const fetchVoiceList = async () => {

  try {

   const response = await getVoices({
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value
    });

    console.log(response.data.data)

    if(response.data.code == 200){ 
      voiceList.value = response.data.data.list
      total.value = response.data.data.total
    }
  } catch (error) {
    console.error('获取语音列表失败:', error);
    ElMessage.error('获取语音列表失败');
  }
};

// 将文件路径转换为可播放的 URL（可根据需求做处理）
const getAudioUrl = (filePath) => {
  if (!filePath) return '';
  // 假设 filePath 返回的是本地磁盘路径，提取文件名
  const fileName = filePath.split('\\').pop();
  console.log(fileName)
  return `http://localhost:9090/${fileName}`;
}

// 编辑操作：复制记录数据并打开编辑对话框
const handleEdit = (record) => {

  currentRecord.value = { ...record }
  editDialogVisible.value = true
    console.log(currentRecord.value.id)
}

// 保存编辑后的数据，调用更新接口
const saveEdit = async () => {
  console.log(currentRecord.value.id)
  try {
     const requestData = {
      id: currentRecord.value.id,   // 必须包含 id
      text: currentRecord.value.text
    };

    // 调用封装的函数
    const response = await updateVoices(requestData);

    console.log('响应数据:', response.data);
    if(response.data.code == 200){
      ElMessage.success('保存成功');
      editDialogVisible.value = false;
      fetchVoiceList();
    }
  } catch (error) {
    // 详细错误提示
    console.error('保存失败:', error);
    ElMessage.error(`保存失败: ${error.response?.data?.message || error.message}`);
  }
};

// 删除操作，调用删除接口
const handleDelete = (record) => {
  ElMessageBox.confirm('此操作将删除该语音记录, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteUser(record.id)
      if(response.data.code == 200){
          ElMessage.success('删除成功')
          fetchVoiceList()
      }

    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消操作，不做处理
  })
}


// 初始化加载用户列表
onMounted(() => {
  fetchVoiceList();
});
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>